<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId">
    <template v-slot:common >
      <div class="wb-calendar" >
        <van-calendar v-model="show"
          :title="title"
          :type="type"
          :default-date="defaultDate"
          :min-date="minDate" 
          :max-date="maxDate"
          :row-height="rowHeight"
          :formatter="formatter"
          :poppable="poppable"
          :show-mark="showMark"
          :show-title="showTitle"
          :show-subtitle="showSubtitle"
          :show-confirm="showConfirm"
          :readonly="readonly"
          :first-day-of-week="firstDayOfWeek"
        />
      </div>
    </template>
  </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import { utils } from '@/components/utils/utils'
import { commonUtils } from '@/components/utils/common-utils'
import { CALENDER_TYPE_MAP } from '@/common/const'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { CONTROL_TYPES } from '@/common/const-wb'
import { reactive } from 'vue'
import { getPxOVwByValue, getPxOrVw } from '@/store/utils'
import { EventBus } from '@/store/index'

export default {
  name: "WbCalendar",
  mixins: [utils, commonUtils],
  setup () {
     const state = reactive({
      show: false,
      date: '',
      title: '日历',
      type: 'single',//single表示选择单个日期，multiple表示选择多个日期，range表示选择日期区间
      defaultDate: null,
      // formatter:日期格式化函数
      poppable: false,//是否以弹层的形式展示日历
      showMark: false,//是否显示月份背景水印
      showTitle: true,//是否展示日历标题
      showSubtitle: true,//是否展示日历副标题（年月）
      showConfirm: false,//是否展示确认按钮
      readonly: true,//是否为只读状态，只读状态下不能选择日期
      // confirm-text	确认按钮的文字
      // confirm-disabled-text	确认按钮处于禁用状态时的文字
      firstDayOfWeek: 0, //设置周起始日
    })
    return state
  },
  components: {
    InjectTemplate,
  },
  created(){
    if(this.isH5Edit) {
      EventBus.$on('refreshCommonAttr', this.onRefreshCommonAttr);
    }
    this.onRefreshCommonAttr();
    // 设置当天voteId
    let date = this.date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let month_ = month <= 9 ? "0" + month.toString() : month.toString();
    let day_ = day <= 9 ? "0" + day.toString() : day.toString();
    let voteId = this.item.commonAttr.voteId = year.toString() + month_ + day_;

    let d = new Date(year, month, 0);
    let days = d.getDate();

    this.dateMinStr = year + "/" + month + "/" + 1;
    this.dateMaxStr = year + "/" + month + "/" + days;

    let lists = this.lists;
    for(let i = 0; i < lists.length; i++){
      if(lists[i].voteId == voteId){
        this.item.commonAttr.itemIndex = i;
        break;
      }
    }
    if(this.item.interactionData) {
      this.createClass()
    }
  },
  computed: {
    rowHeight() {
      if(this.isH5Edit) {
        return MOBILE_WID_HEI.width * 0.11285;
      }else {
        let reallyWidth = MOBILE_WID_HEI.clientWidth
        reallyWidth *= 0.11285;
        return reallyWidth;
      }
    },
    minDate(){
      let minDate = "";
      if(this.commonAttr.calendarType == CALENDER_TYPE_MAP.currentMonth){
        minDate = this.dateMinStr;
      }else{
        minDate = this.commonAttr.minDate;
      }
      let arr = minDate.split("/");
      return new Date(arr[0], arr[1]-1, arr[2]);
    },
    maxDate(){
      let maxDate = "";
      if(this.commonAttr.calendarType == CALENDER_TYPE_MAP.currentMonth){
        maxDate = this.dateMaxStr;
      }else{
        maxDate = this.commonAttr.maxDate;
      }
      let arr = maxDate.split("/");
      return new Date(arr[0], arr[1]-1, arr[2]);
    },
  },
  methods: {
    onRefreshCommonAttr() {
      document.documentElement.style.setProperty(`--calendar-bg-color`, this.commonAttr.backgroundColor);
      document.documentElement.style.setProperty(`--calendar-color`, this.commonAttr.color);
      if(this.commonAttr.selectedBackgroundColor) {
        document.documentElement.style.setProperty(`--calendar-selected-bg-color`, this.commonAttr.selectedBackgroundColor);
      }
      if(this.commonAttr.selectedBorderUrl) {
        document.documentElement.style.setProperty(`--calendar-selected-border-url`, "url(" + this.commonAttr.selectedBorderUrl + ")");
        document.documentElement.style.setProperty(`--calendar-selected-border-size`, 0);
      } else {
        document.documentElement.style.setProperty(`--calendar-selected-border-url`, "url()");
        document.documentElement.style.setProperty(`--calendar-selected-border-size`, getPxOVwByValue(2));
        document.documentElement.style.setProperty(`--calendar-selected-border-color`, this.commonAttr.selectedBorderColor);
      }
      document.documentElement.style.setProperty(`--calendar-selected-color`, this.commonAttr.selectedColor);
      document.documentElement.style.setProperty(`--calendar-font-size`, this.commonAttr.fontSize + getPxOrVw());
    },
    formatDate(date) {
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    onConfirm(date) {
      const [start, end] = date;
      this.date = `${this.formatDate(start)} - ${this.formatDate(end)}`;
    },
    formatter(day) {
      // date	日期对应的 Date 对象
      // type	日期类型，可选值为selected、start、middle、end、disabled
      // topInfo 上方的提示信息
      // bottomInfo 下方的提示信息
      // text	中间显示的文字
      // className	额外类名
      const year = day.date.getFullYear();
      const month = day.date.getMonth() + 1;
      const month_ = month <= 9 ? "0" + month : month;
      const date = day.date.getDate();
      const date_ = date <= 9 ? "0" + date : date;

      // if (month === 5) {
      //   if (date === 1) {
      //     day.topInfo = '劳动节';
      //   } else if (date === 4) {
      //     day.topInfo = '青年节';//上方的提示信息
      //   }
      // }

      // if (day.type === 'start') {
      //   day.bottomInfo = '入住';
      // } else if (day.type === 'end') {
      //   day.bottomInfo = '离店';//下方的提示信息
      // }else
      let currentDate = new Date();
      let elements = this.getItemControls && this.getItemControls[CONTROL_TYPES.vote].data.elements;
      if(elements && elements[year.toString() + month_ + date_] && elements[year.toString() + month_ + date_].num > 0){
        day.type = "selected"
        day.topInfo = month + '月';
      }else if (date === currentDate.getDate() && month == currentDate.getMonth() + 1) {
        day.text = '今天';
        // day.type = "selected"
        // day.topInfo = month + '月';
      }
      //根据条件显示签到天数
      let lists = this.item.interactionData && this.item.interactionData.lists
      if(lists && lists.length > 0){
        let key = Number(date_) - 1
        if(lists[key] && lists[key].url && lists[key].url.length > 0){
          day.text = ''
          day.topInfo =''
          day.className = `calendar-item-bg-${key}`
        }
      }
      return day;
    },
    createClass() {
      let lists = this.item.interactionData.lists
      if(lists && lists.length > 0) {
        let innerHTML = ''
        for(let i = 0; i < lists.length; i++){
          if(lists[i].url && lists[i].url.length == 0)
            break;
            innerHTML = innerHTML + `.calendar-item-bg-${i} { border-radius: 50%;
                        width: 11.285%;
                        margin: 1.5%;
                        background:url(${lists[i].url}) ;background-size: contain;}`; 
        }
        this.loadStyleString(innerHTML)
      }
    },
  },
  beforeUnmount() {
    if(this.isH5Edit) {
      EventBus.$off('refreshCommonAttr', this.onRefreshCommonAttr);
    }
  }
};
</script>

<style lang="scss">
:root{
  --calendar-bg-color: #f2f2f2;
  --calendar-selected-bg-color: transparent;
  --calendar-selected-border-color: green;
  --calendar-selected-border-size: var(--size-2);
  --calendar-selected-border-url: url();//https://static.hd.xxx.com/upload/biz/14/55328798_350.png
  --calendar-color: #000;
  --calendar-selected-color: #cf8910;
  --calendar-font-size: var(--size-28);
}
.wb-calendar {
  width: inherit;
  height: inherit;

  .van-calendar__day {
    border-radius: 50%;
    color: var(--calendar-color);
    background-color: var(--calendar-bg-color);
    font-size: var(--calendar-font-size);
    width: 11.285%;
    margin: 1.5%;
  }

  .van-calendar__day--start{
    border-radius: var(--size-8) 0 0 var(--size-8);
  }

  .van-calendar__selected-day{
    padding-top: var(--size-8);
    color: var(--calendar-selected-color);
    background-color: var(--calendar-selected-bg-color);
    border: var(--calendar-selected-border-size) solid var(--calendar-selected-border-color);
    background-image: var(--calendar-selected-border-url);
    background-size: cover;
  }
  .van-calendar__body{
    margin-top: var(--size-40);
  }
}
</style>
